<template>
  <el-drawer v-model="visible" :size="size" @close="close">
    <!-- 抽屉标题 -->
    <template #header="{ close }">
      <el-page-header @back="close">
        <template #content>
          <span class="text-large font-600 mr-3">{{ title }}</span>
        </template>
      </el-page-header>
    </template>
    <!-- 动态加载的组件 -->
    <component
      :is="currentComponent"
      v-if="currentComponent"
      v-bind="currentProps"
    />
  </el-drawer>
</template>

<script setup>
import componentRegistry from "@/drawerRoute"; // 引入 drawerRoute 映射
import { ref, defineExpose, shallowRef, markRaw } from "vue";

// 抽屉状态和属性
const visible = ref(false);
const title = ref("");
const currentComponent = shallowRef(null);
const currentProps = ref({});
const size = ref("50%");

// 打开抽屉
const open = async options => {
  visible.value = true;
  title.value = options.title || "Drawer";
  const componentLoader = componentRegistry[options.component];
  if (componentLoader) {
    // 动态加载组件
    const loadedComponent = (await componentLoader()).default;
    currentComponent.value = markRaw(loadedComponent);
  } else {
    console.error(`组件 "${options.component}" 在组件注册表中找不到。`);
    currentComponent.value = null;
  }
  currentProps.value = options.props || {};
};

// 关闭抽屉
const close = () => {
  visible.value = false;
  title.value = "";
  currentComponent.value = null;
  currentProps.value = {};
};

// 暴露方法给父组件
defineExpose({
  open,
  close
});
</script>

<style scoped></style>
